var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var jwt = require("jsonwebtoken");
var app = express();
// cors
var cors = require("cors")
app.use(cors())

// 自定义中间件 用于处理jwt验证
app.use((req,res,next)=>{
  // 定义不需要验证的路径
  let pathArr=[
    '/userLogin',
    '/refresh',
    '/sendYzm',
    '/resetPassword',
    '/findUser',
    '/upload'
  ]

  // 如果请求路径在不需要验证的路径中，直接调用next（）继续处理
  if(pathArr.includes(req.path)){
    return next()
  }

  // 获取请求头中的accessToken和refreshToken
  const accessToken = req.headers.accesstoken
  const refreshToken = req.headers.refreshtoken
  

  // 判断refreshToken是否过期
  try{
    jwt.verify(refreshToken,"MTHGH")
  }catch(error){
    console.log(error,111);
    return res.status(403).send({message:'refreshToken验证失败'})
  }

  // 如果没有accessToken 返回401
  if(!accessToken){
    return res.status(401).send({message:'未获取到accessToken'})
  }
// 使用中间件
// app.use('/index',validateRefreshToken,validateAccessToken)
// app.use('/user',validateRefreshToken,validateAccessToken)
  // 验证accessToken
  try{
    const user = jwt.verify(accessToken,"MTHGH")
    res.locals.user = user//将用户信息存储在res.locals中，供后续中间件使用
    return next()
  }catch(error){
    return res.status(401).send({message:'accessToken验证失败'})
  }
})


// token
// var expressJWT = require("express-jwt")
// app.use(expressJWT({
//     secret: "123",
//     algorithms: ["HS256"]
// }).unless({
//     path: ["/login", "/upload", {url: /^\/upload/, methods: ['GET']}]
// }))

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use( '/upload', express.static(path.join(__dirname, 'upload')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
